package com.itheima.reggie.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.itheima.reggie.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.security.SecureRandom;
import java.util.UUID;

/*
支付宝沙箱支付
1.APP_ID 应用ID
2.APP_PRIVATE_KEY 应用私钥
3.ALIPAY_PUBLIC_KEY 应用公司
4.RETURN_URL 付款成功回调页面
 */
@RestController
public class PayController {

    @Autowired
    private OrderService orderService;


    private final String APP_ID = "2021000120611479";
    private final String APP_PRIVATE_KEY = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCbGBnhaHSw+gAW7WczXyjd3YNiLUdQzkOgGdW6axR6JFvcjd/wSAtbjhOvRwarypPJ9UCD0Kksl5ricoKR5oh8yaiKi+kqa+PORGu3p6d9WPDoA/7T2Btzbvy+ngX8wGyhdKJDw9HchXZi48TK/H1zku7d62ZblSnXpz3PcNNube6yijaU/gNUcv3/9JxNw53s+CHZoF0q7C3zE7OIU9vxCUaQU4NrFmBk1np5Jg0IWIhvLWSk8sbqSp20RZD8W+TEG7ILHk2YMmSDl59peuj/D1UP7Mg4y7xR/G0L9vAxUQUbq+5M5tf9IssleTCqKBatvNJmMjEnWrSsHhUign5rAgMBAAECggEBAIuQDon2EzvGXBpFm55wvTeZQ8cu84PVeKkzVk6gWRbobPl1edShIAdNPI13npssef08gsebFwEXk7q+TJy6FIwmc1HpQPJ5j89nZn8nkOKNDIvcPI2pZFplv25QiRa+mYJYkEPmjIyiVLv8NnRq7QD5cZWlZMB44+Q5jLeE0d4GCyJx6tFH47bwOSnf2hg0uguRZUGYMBz4rcj1Vue7wSfPiFpBVBoiRTFoYFl22ovMN4x5rtGWHhMNNIJsHWryBttKkk2tJakdW0dI+JDnpwnuw/G0QEU6eJIuUVRYlzlZ3QY+jAlMP0JP9k7Tezp/XJ9MwzLdAQJbNA8TDkqDR/ECgYEA1xThCzORLw0ubV33kvpdRg8vukmpscG/OIBHrMbBIftzaXpijvnvNvQm6ucf+m1Wo5pV/Sp4chkayJZJtP+0ZR9BashgKmV0xY0QEE9Hb2zn0+G4DaI19yhv2z1IxLwHzgys6oWHR/1SlPmrcqjHGjY/dIVxQLQvWLkQjXnj/s0CgYEAuJmnaQZXY7lbBAEyfYgEPOZAAFcZqJEd+rqA8mSHC6gof5VvSm3GLjU3piKUOnGDiIGYVYTbcoMxWFOgO32f7c9nk4d4XWQgg3cJTOMJOImT2pnVUyNkTVwDMx7vaBePs273bzDLiRhF9/9T6Q7402zQU+d49YXXzcZzHBEtAhcCgYEA1VvM8sOw3jABQlTY52CdboZaHj48rC06d94pO+feZst97cCOTK768lS41oV4X4BfVeQgMQgUe3sT6q/LZlXSqg2bY0ZqvyPt9pq8uLEseAhc4P8lCcFEL25Zp+7fZOnyBCDm166mSG+voEEcJp3vBL2TrQ9DDaCw5x6OoQmtdnECgYB6rhLl50L4kVx9YtZNOrGmT1bFYx04O4jy8jNz438kLhMMByG5Ew8b8l4TWPOti3bgp0+3td2pUqreimT4ZFp+ztGE6AkD9+DrvZY+tLuSCUxrgMSWxfSIvNebh7mPMelcVCi4inMZnzoQwGzhfAO9bplcyX5HnTV4GaSySG/i7QKBgBcxVJx/7pMFTeaF+Kqn8skIqt09JIme8i0um/sQldPawdcjORMPUfqYs2G0sejbr6Aood/VowWHuEJYhsAjX0N84MHCorp2m+mBVahv03pT2fCJKp2x+7NwEQFDsz2c9kdAOkeUIi5xW7V2XXC3JOaCkf7+ZdEDDMTHXspqoMUx";
    private final String CHARSET = "UTF-8";
    private final String ALIPAY_PUBLIC_KEY = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAmxgZ4Wh0sPoAFu1nM18o3d2DYi1HUM5DoBnVumsUeiRb3I3f8EgLW44Tr0cGq8qTyfVAg9CpLJea4nKCkeaIfMmoiovpKmvjzkRrt6enfVjw6AP+09gbc278vp4F/MBsoXSiQ8PR3IV2YuPEyvx9c5Lu3etmW5Up16c9z3DTbm3usoo2lP4DVHL9//ScTcOd7Pgh2aBdKuwt8xOziFPb8QlGkFODaxZgZNZ6eSYNCFiIby1kpPLG6kqdtEWQ/FvkxBuyCx5NmDJkg5efaXro/w9VD+zIOMu8UfxtC/bwMVEFG6vuTObX/SLLJXkwqigWrbzSZjIxJ1q0rB4VIoJ+awIDAQAB";
    //这是沙箱接口路径,正式路径为https://openapi.alipay.com/gateway.do
    private final String GATEWAY_URL ="https://openapi.alipaydev.com/gateway.do";
    private final String FORMAT = "JSON";
    //签名方式
    private final String SIGN_TYPE = "RSA2";
    //支付宝异步通知路径,付款完毕后会异步调用本项目的方法,必须为公网地址
    private final String NOTIFY_URL = "http://127.0.0.1/notifyUrl";
    //支付宝同步通知路径,也就是当付款完毕后跳转本项目的页面,可以不是公网地址
    private final String RETURN_URL = "http://localhost/front/page/pay-success.html";



    @RequestMapping("aliapy")
    public void alipay(HttpServletResponse httpResponse) throws IOException {

        SecureRandom r= new SecureRandom();
        //实例化客户端,填入所需参数
        AlipayClient alipayClient = new DefaultAlipayClient(GATEWAY_URL, APP_ID, APP_PRIVATE_KEY, FORMAT, CHARSET, ALIPAY_PUBLIC_KEY, SIGN_TYPE);
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        //在公共参数中设置回跳和通知地址
        request.setReturnUrl(RETURN_URL);
        request.setNotifyUrl(NOTIFY_URL);

        //商户订单号，商户网站订单系统中唯一订单号，必填
        //生成随机Id
        String out_trade_no = UUID.randomUUID().toString();
        //付款金额，必填
        //String total_amount =Integer.toString(r.nextInt(1)+1);
        String amount =orderService.getAmount();
        String total_amount=amount;
        //订单名称，必填
        String subject ="菩提阁美食";
        //商品描述，可空
        String body = "尊敬的会员欢迎订购菩提阁美食";
        request.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                + "\"total_amount\":\""+ total_amount +"\","
                + "\"subject\":\""+ subject +"\","
                + "\"body\":\""+ body +"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        String form = "";
        try {
            form = alipayClient.pageExecute(request).getBody(); // 调用SDK生成表单
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        httpResponse.setContentType("text/html;charset=" + CHARSET);
        httpResponse.getWriter().write(form);// 直接将完整的表单html输出到页面
        httpResponse.getWriter().flush();
        httpResponse.getWriter().close();
    }

}
